package com.sdksoft.readcard

import android.content.Intent
import android.graphics.BitmapFactory
import android.text.TextUtils
import android.view.View
import com.csht.bean.EPassportData
import com.csht.bean.IdCardData
import com.csht.bean.isOutTime
import com.csht.constants.Constant
import com.csht.enums.ReadCardType
import com.csht.enums.StatusCode
import com.csht.listener.InitListener
import com.csht.listener.ReadCardListener
import com.csht.local.ble.Ble2Manager
import com.csht.local.ble.zg.BleZGManager
import com.sdksoft.readcard.databinding.ActivityBle2Binding
import com.csht.utils.HHTipUtils
import com.siecom.framework.device.SiecomDevice
import java.util.Locale

/**
 * 蓝牙读卡器读卡
 */
class Ble2Activity : BaseInitActivity(), ReadCardListener {

    private val TAG = "readcard"

    private lateinit var activityBle2Binding: ActivityBle2Binding

    private var isInitOk = false

    private var bleType = 0 // 0:DK蓝牙  1: 背夹蓝牙

    override fun initView() {
        super.initView()
        setTitleText("蓝牙读卡")
        bleType = intent.getIntExtra("bleType", 0)
        activityBle2Binding = ActivityBle2Binding.inflate(layoutInflater)
        baseActivityBinding.llContent.apply {
            addView(activityBle2Binding.root, 0)
        }
        activityBle2Binding.apply {
            buDevice.setOnClickListener {
                startActivityForResult(Intent(this@Ble2Activity, Ble2ScanActivity::class.java), 101)
            }
            buVoltage.setOnClickListener {
                readCardManager.getBLEVoltage {
                    activityBle2Binding.ivHead.setImageResource(0)
                    activityBle2Binding.tvMsg.text = "电池电压：$it"
                }
            }
            buName.setOnClickListener {
                val name = bleName.text.toString().trim()
                if (TextUtils.isEmpty(name)) {
                    HHTipUtils.getInstance().showToast(this@Ble2Activity, "请输入蓝牙名称")
                    return@setOnClickListener
                }
                readCardManager.changeBleName(name) { result, msg ->
                    HHTipUtils.getInstance().showToast(this@Ble2Activity, msg)
                }
            }
            buOne.setOnClickListener {
                activityBle2Binding.ivHead.setImageResource(0)
                if (!isInitOk) {
                    if (readCardManager.readCardType() == ReadCardType.BLE && Ble2Manager.init.isConnect()){
                        initSDK()
                        return@setOnClickListener
                    }
                    if (readCardManager.readCardType() == ReadCardType.BLE_ZG_BJ  && BleZGManager.init.isConnected()) {
                        initSDK()
                        return@setOnClickListener
                    }
                    activityBle2Binding.tvMsg.text = "请先连接蓝牙设备"
                    HHTipUtils.getInstance().showToast(this@Ble2Activity, "请先连接蓝牙设备")
                    return@setOnClickListener
                }
                activityBle2Binding.tvMsg.text =
                    "开始读取身份证/永居证/银行卡\n云解码需要连接网络，请确保设备已连接良好的网络"
                if (readCardManager.readCardType() == ReadCardType.BLE_ZG_BJ) {
                    readCardManager.readCardOnceStart(this@Ble2Activity)
                } else {
                    readCardManager.readCardStart(this@Ble2Activity)
                }
            }
            btnPassport.setOnClickListener {
                activityBle2Binding.ivHead.setImageResource(0)
                if (!isInitOk) {
                    if (readCardManager.readCardType() == ReadCardType.BLE && Ble2Manager.init.isConnect()){
                        initSDK()
                        return@setOnClickListener
                    }
                    if (readCardManager.readCardType() == ReadCardType.BLE_ZG_BJ  && BleZGManager.init.isConnected()) {
                        initSDK()
                        return@setOnClickListener
                    }
                    activityBle2Binding.tvMsg.text = "请先连接蓝牙设备"
                    HHTipUtils.getInstance().showToast(this@Ble2Activity, "请先连接蓝牙设备")
                    return@setOnClickListener
                }
                val documentNumberStr =
                    documentNumber.text.toString().trim().toUpperCase(Locale.ROOT)
                val dateOfBirthStr = dateOfBirth.text.toString().trim()
                val dateOfExpiryStr = dateOfExpiry.text.toString().trim()
                if (documentNumberStr.isEmpty() || dateOfBirthStr.isEmpty() || dateOfExpiryStr.isEmpty()) {
                    HHTipUtils.getInstance().showToast(this@Ble2Activity, "请完整填写参数")
                    return@setOnClickListener
                }
                activityBle2Binding.tvMsg.text =
                    "开始读取护照/通行证\n护照/通行证，照片较大读取时间较长，读取过程中，请不要移动读卡设备和护照/通行证。"
                // 开始读取护照
                readCardManager.readPassportStart(
                    intent, documentNumberStr, dateOfBirthStr, dateOfExpiryStr, this@Ble2Activity
                )
            }
//            documentNumber.setText("")
//            dateOfBirth.setText("")
//            dateOfExpiry.setText("")
            checkBoxHead.isChecked = Constant.isPassportPhoto
            checkBoxHead.setOnCheckedChangeListener { buttonView, isChecked ->
                Constant.isPassportPhoto = isChecked

            }
        }
        when (bleType) {
            0 -> {
                readSettingBuilder.buildReadCardType(ReadCardType.BLE)
            }

            1 -> {
                activityBle2Binding.apply {
                    readSettingBuilder.buildReadCardType(ReadCardType.BLE_ZG_BJ)
                    buOne.text = "背夹蓝牙读身份证"
                    buVoltage.visibility = View.GONE
                    checkBoxHead.visibility = View.GONE
                    llBleName.visibility = View.GONE
                    documentNumber.visibility = View.GONE
                    dateOfBirth.visibility = View.GONE
                    dateOfExpiry.visibility = View.GONE
                    btnPassport.visibility = View.GONE
                }
            }

            else -> {
                readSettingBuilder.buildReadCardType(ReadCardType.BLE)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101) {
            if (readCardManager.readCardType() == ReadCardType.BLE && Ble2Manager.init.isConnect()){
                initSDK()
            }
            else if (readCardManager.readCardType() == ReadCardType.BLE_ZG_BJ  && BleZGManager.init.isConnected()) {
                initSDK()
            } else {
                HHTipUtils.getInstance().showToast(this, "蓝牙未连接，请先连接蓝牙设备")
            }
        }
    }

    /**
     * 初始化SDK
     */
    private fun initSDK() {
        if (readCardManager.readCardType() === ReadCardType.BLE || readCardManager.readCardType() === ReadCardType.BLE_ZG_BJ) {
            readCardManager.readCardInit(object : InitListener {
                override fun onResponse(code: Int, msg: String) {
                    when (code) {
                        StatusCode.ININ_ING.code -> { // 初始化中...
                            isInitOk = false
                            runOnUiThread {
                                activityBle2Binding.tvMsg.apply {
                                    append("\r\n")
                                    append(msg)
                                }
                            }
                        }

                        StatusCode.ININ_OK.code -> {
                            isInitOk = true
                            runOnUiThread {
                                HHTipUtils.getInstance().showToast(this@Ble2Activity, "初始化成功")
                                activityBle2Binding.tvMsg.apply {
                                    append("\r\n")
                                    append("初始化成功")
                                }
                            }
                        }

                        else -> {
                            isInitOk = false
                            runOnUiThread {
                                HHTipUtils.getInstance().showToast(this@Ble2Activity, "初始化失败")
                                activityBle2Binding.tvMsg.apply {
                                    append("\r\n")
                                    append(msg.ifEmpty { "初始化失败" })
                                }
                            }
                        }
                    }
                }
            })
        } else {
            HHTipUtils.getInstance().showToast(this, "请选择蓝牙读卡类型")
        }
    }

    override fun onReadCardState(type: Int, msg: String?) {
        if (type == StatusCode.READCARD_FAILE.code) {
            HHTipUtils.getInstance().dismissProgressDialog()
            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
        } else if (type == StatusCode.READCARD_SUCCESS.code) {
            HHTipUtils.getInstance().dismissProgressDialog()
            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
        } else if (type == StatusCode.FIND_CARD_SUCCESS.code) {
            if (!HHTipUtils.getInstance().progressDialogIsShowing()) {
                HHTipUtils.getInstance().showProgressDialog(this, "正在读取,请勿移动")
            }
        }
        if (type != StatusCode.READCARD_SUCCESS.code && !isOutTime(msg ?: "")) {
            activityBle2Binding.tvMsg.apply {
                append("\n状态码：$type")
                append("\n消息：$msg")
                append("\n-------------------------")
            }
            mainHandler.postDelayed(
                {
                    activityBle2Binding.logScroll.fullScroll(View.FOCUS_DOWN)
                },
                200
            )
        }
    }

    override fun onReadICCardSuccess(icNumber: String?, type: Int) {
        HHTipUtils.getInstance().dismissProgressDialog()
        activityBle2Binding.tvMsg.apply {
            text = "读取成功："
            append("\n卡号：")
            append(icNumber)
            append("\n卡类型：")
            append(type.toString())
            append("\n-------------------------")
        }
        activityBle2Binding.ivHead.setImageResource(0)
    }

    override fun onReadIDCardSuccess(bean: IdCardData?) {
        HHTipUtils.getInstance().dismissProgressDialog()
        bean?.apply {
            bitmap?.let { bitmap ->
                activityBle2Binding.ivHead.setImageBitmap(bitmap)
            }
            activityBle2Binding.tvMsg.apply {
                text = "读取成功："
                when (type) {
                    StatusCode.CARD_IDCARD_FOREIGN.code,
                    StatusCode.CARD_IDCARD_FOREIGN_OLD.code -> { // 外国永久居住证
                        append("\n中文姓名：")
                        append(nameChinese)
                        append("\n英文姓名：")
                        append(nameEnglish)
                        append("\n性别：")
                        append(sex)
                        append("\n生日：")
                        append(birthday)
                        append("\n国籍：")
                        append(nationlity)
                        append("\n证件号码：")
                        append(bean.id)
                        append("\n有效期限：")
                        append(startDate)
                        append(" - ")
                        append(endDate)
                    }

                    StatusCode.CARD_IDCARD.code, StatusCode.CARD_IDCARD_GAT.code -> { // 中国居民身份证
                        append("\n姓名：")
                        append(name)
                        append("\n性别：")
                        append(sex)
                        append("\n民族：")
                        append(nation)
                        append("\n生日：")
                        append(birthday)
                        append("\n住址：")
                        append(address)
                        append("\n证件号码：")
                        append(bean.id)
                        append("\n签发机关：")
                        append(bean.issue)
                        append("\n有效期限：")
                        append(startDate)
                        append(" - ")
                        append(endDate)
                    }
                }

                append("\n\n耗时：$distime ms")
            }
        }
    }

    override fun onReadPassportSuccess(bean: EPassportData?) {
        super.onReadPassportSuccess(bean)
        HHTipUtils.getInstance().dismissProgressDialog()
        bean?.apply {
            activityBle2Binding.tvMsg.apply {
                text = "姓名："
                append(nameOfHolder)
                append(" / $primaryIdentifier $secondaryIdentifier")
                append("\n性别：")
                append(if (gender.startsWith("M")) "男" else "女")
                append(" / $gender")
                append("\n生日：")
                append(dateOfBirth)
                append("\n国家码：")
                append(nationality)
                append("\n有效期：")
                append(dateOfExpiry)
                append("\n护照号码：")
                append(documentNumber)
                append("\n个人号码：")
                append(personNumber)
                append("\n护照机读码：")
                append(mrz)
//                if (passiveAuth) {
//                    append("\n\npassiveAuthStr: pass")
//                } else {
//                    append("\n\npassiveAuthStr: failed")
//                }
//                if (chipAuth) {
//                    append("\nchipAuthStr: pass")
//                } else {
//                    append("\nchipAuthStr: failed")
//                }
                append("\n\n耗时：$duration ms")
            }
//            if (headBitmap == null) {
//                activityBle2Binding.ivHead.setImageResource(0)
//            } else {
//                headBitmap?.let { bitmap ->
//                    activityBle2Binding.ivHead.setImageBitmap(bitmap)
//                }
//            }
            if (image == null) {
                activityBle2Binding.ivHead.setImageResource(0)
            } else {
                image?.let {
                    val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
                    activityBle2Binding.ivHead.setImageBitmap(bitmap)
                }
            }
        }
    }

    override fun onDestroy() {
        HHTipUtils.getInstance().dismissProgressDialog()
        mainHandler.removeCallbacksAndMessages(null)
        readCardManager.readCardStop()
        readCardManager.readCardReleaseDestory()
        if (readCardManager.readCardType() == ReadCardType.BLE_ZG_BJ  && BleZGManager.init.isConnected()){
            BleZGManager.init.disConnectBtDevice()
        }
        super.onDestroy()
    }
}